#!/data/data/com.termux/files/usr/bin/bash
folder=arch-arm64
file=start-arch.sh
who="科技猫"
tarball="rootfs.tar.gz"
if [ -d "$folder" ]; then
	first=1
fi

if [ "$first" != 1 ];then
	if [ ! -f $tarball ]; then
		echo "$who正在准备镜像…"
		wget "https://mirrors.tuna.tsinghua.edu.cn/archlinuxarm/os/ArchLinuxARM-zedboard-latest.tar.gz" -O $tarball
	fi
	cur=`pwd`
	mkdir -p "$folder"
	cd "$folder"
	echo "$who正在解压rootfs…"
	
	proot --link2symlink tar -xzf ${cur}/${tarball}||:
	cd "$cur"
fi

echo "writing launch script"
cat > "$file" <<- 'EOM'
#!/bin/bash
cd "$(dirname "$0")" || exit 1
## For rooted user: pulseaudio --start --system
## unset LD_PRELOAD in case termux-exec is installed
unset LD_PRELOAD
command="proot"
command+=" --link2symlink"
command+=" -0"
command+=" -r arch-arm64"
command+=" -b /dev"
command+=" -b /proc"
command+=" -b arch-arm64/root:/dev/shm"
## uncomment the following line to have access to the home directory of termux
#command+=" -b /data/data/com.termux/files/home:/root"
## uncomment the following line to mount /sdcard directly to / 
#command+=" -b /sdcard"
command+=" -w /root"
command+=" /usr/bin/env -i"
command+=" HOME=/root"
command+=" PATH=/usr/local/sbin:/usr/local/bin:/bin:/usr/bin:/sbin:/usr/sbin:/usr/games:/usr/local/games"
command+=" TERM=$TERM"
command+=" LANG=zh_CN.UTF-8"
command+=" /bin/bash --login"
com="$*"
if [ -z "$1" ]; then
    exec $command
else
    $command -c "$com"
fi
EOM

# 检查容器是否存在
if [ ! -d "$folder" ]; then
    echo -e "错误: 容器路径 $folder 不存在"
    exit 1
fi

echo -e "开始修复 Proot 容器 DNS 问题..."

rm -rf ./$folder/etc/resolv.conf
cat << EOF > "./$folder/etc/resolv.conf"
nameserver 1.1.1.1
nameserver 1.0.0.1
nameserver 8.8.8.8
nameserver 8.8.4.4
options edns0 single-request-reopen
EOF

chmod 644 "./$folder/etc/resolv.conf"

echo "正在制作可执行的$file"
chmod +x ./$file
echo "正在移除镜像…"
rm $tarball
echo "正在进行一些必要的调整"
rm ./arch-arm64/etc/pacman.d/mirrorlist
wget https://gitee.com/scicat-team/arch-for-termux/raw/master/mirrorlist -O ./arch-arm64/etc/pacman.d/mirrorlist
rm ./arch-arm64/etc/pacman.conf
wget https://gitee.com/scicat-team/arch-for-termux/raw/master/pacman.conf -O ./arch-arm64/etc/pacman.conf
echo "OK，你可以使用 ./$file 命令启动它了。我们已经帮你打开了它。"
rm $0
./$file